前幾天已經學會 Python 的變數、List、Dictionary、流程控制和 Function,今天開始讓 Python 實際接觸資料。
因為這次 30 天的主題是「Python 爬蟲與資料分析」,之後從網站取得資料後,不可能只把資料留在程式裡,還需要把資料儲存下來,之後才能進一步整理和分析。
今天主要學習兩種常見的資料格式:CSV 和 JSON。
一、CSV 是什麼?
CSV(Comma-Separated Values)可以把它想成一個簡單的表格。
例如:
name,price,rating
無線耳機,1990,4.5
機械鍵盤,2500,4.7
滑鼠,890,4.3
每一列代表一筆資料,而不同欄位通常使用逗號分隔。
今天我先使用 Python 的 csv 模組,在 Google Colab 建立一個商品資料的 CSV 檔案。
import csv
products = [
["無線耳機", 1990, 4.5],
["機械鍵盤", 2500, 4.7],
["滑鼠", 890, 4.3]
]
with open("products.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["name", "price", "rating"])
writer.writerows(products)
print("CSV 建立完成!")
執行後,可以在 Google Colab 左側的檔案區看到 products.csv。
二、讀取 CSV
建立完成後,我再練習把 CSV 資料讀取回來。
import csv
with open("products.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
for row in reader:
print(row)
執行後可以看到:
['name', 'price', 'rating']
['無線耳機', '1990', '4.5']
['機械鍵盤', '2500', '4.7']
['滑鼠', '890', '4.3']
這裡有一個需要注意的地方,從 CSV 讀取回來的資料通常會是字串。
例如:
'1990'
和:
1990
是不一樣的資料型態。
如果之後需要拿價格進行數學運算,就需要再進行資料型態轉換。
三、JSON 是什麼?
接著開始學習 JSON。
JSON 也是網路資料中很常見的一種格式,而且它的結構和 Python Dictionary 很像。
例如:
{
"name": "無線耳機",
"price": 1990,
"rating": 4.5
}
這和之前學過的 Python Dictionary:
product = {
"name": "無線耳機",
"price": 1990,
"rating": 4.5
}
看起來非常相似。
這也讓我比較容易理解 JSON 的資料結構。
四、建立與讀取 JSON
今天也實際練習使用 Python 建立 JSON:
import json
product = {
"name": "無線耳機",
"price": 1990,
"rating": 4.5
}
with open("product.json", "w", encoding="utf-8") as file:
json.dump(product, file, ensure_ascii=False, indent=4)
print("JSON 建立完成!")
其中 ensure_ascii=False 可以讓中文正常顯示,而 indent=4 可以讓 JSON 排版比較容易閱讀。
接著再把 JSON 讀取回來:
import json
with open("product.json", "r", encoding="utf-8") as file:
product = json.load(file)
print(product)
print(product["name"])
print(product["price"])
輸出:
{'name': '無線耳機', 'price': 1990, 'rating': 4.5}
無線耳機
1990
五、把前幾天學的內容結合起來
最後,我把前幾天學過的 List、Dictionary 和 for 迴圈,和今天學到的 CSV 結合起來。
import csv
products = [
{"name": "無線耳機", "price": 1990, "rating": 4.5},
{"name": "機械鍵盤", "price": 2500, "rating": 4.7},
{"name": "滑鼠", "price": 890, "rating": 4.3},
{"name": "USB 麥克風", "price": 1590, "rating": 4.6}
]
with open("products.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["name", "price", "rating"])
for product in products:
writer.writerow([
product["name"],
product["price"],
product["rating"]
])
print("商品資料已經儲存成 CSV!")
這時候我開始看到一個比較完整的資料處理流程:
取得資料
↓
整理資料
↓
儲存成 CSV / JSON
↓
之後使用 Pandas 分析
這其實已經和之後的網路爬蟲流程有點接近了。